import traceback

from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtWidgets import QMessageBox, QHeaderView, QApplication

from base.base import BaseGui
from dao.rapid_bank_db import RapidBankManager
from dao.rapid_crawler_bin_db import RapidCrawlerBinManager
from enums.crawler_bin_enum import CrawlerBinEnum
from rapid_api.crawler_bin_for_bank import get_crawler_bin_total
from utils.button_tablewidget import WithButtonTableWidget
from utils.excel import ExportExcelDialog


class CrawlerBinGui(BaseGui):

    def __init__(self):
        super().__init__()

        self.crawler_bin_page_size = 10  # 默认分页数
        self.crawler_bin_page_num = 1  # 默认分页
        self.crawler_bin_headers = CrawlerBinEnum.getDescList()
        self.crawler_bin_headers.append("操作")
        self.crawlerBinTableWidget = self.ui.crawlerBinTableWidget
        self.crawlerBinTableWidget.keyPressEvent = self.keyPressEventForBinTable
        self.crawler_bin_page_data = None  # 当前页数据

        try:
            # 银行精准查询
            self.ui.BINByBankPushButton.clicked.connect(self.indexCrawlerBinByBank)
            # BIN 查询
            self.ui.BINPushButton.clicked.connect(self.indexByCrawlerBin)
            # 分页展示第一页
            self.crawler_bin_show_page(page_num=self.crawler_bin_page_num)
            # 下一页
            self.ui.crawler_bin_page_down.clicked.connect(self.crawler_bin_page_down)
            # 上一页
            self.ui.crawler_bin_page_up.clicked.connect(self.crawler_bin_page_up)
            # 导出 crawler_bin列表
            self.ui.crawlerExportPushButton.clicked.connect(self.exportCrawlerBins)
            # 一键获取所有银行的数据
            # self.ui.pushButton.clicked.connect(self.oneClickRetrievalBIN)

        except Exception as e:
            traceback.print_exc()
            QMessageBox.about(self.ui, "账号页点击错误", str(e))

    def keyPressEventForBinTable(self, event):
        """ Ctrl + C复制表格内容 """
        if event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_C:
            # 获取剪贴板对象
            clipboard = QApplication.clipboard()
            mimeData = QMimeData()
            # 创建一个文本字符串来保存选中的数据
            text = ''
            for item in self.crawlerBinTableWidget.selectedItems():
                text += item.text() + '\n'  # 使用换行符或其他分隔符
            # 去除末尾可能的多余换行符
            if text.endswith('\n'):
                text = text[:-1]
            # 将文本设置为 MIME 数据
            mimeData.setText(text)
            # 将 MIME 数据设置到剪贴板
            print(text)
            clipboard.setMimeData(mimeData)

    def crawler_bin_show_page(self, page_num):
        self.crawlerBinTableWidget.clear()
        self.crawler_bin_page_data = None
        query_columns = CrawlerBinEnum.getValuesStr()
        start = (page_num - 1) * self.crawler_bin_page_size
        rapidCrawlerBinManager = RapidCrawlerBinManager()
        self.crawler_bin_page_data = rapidCrawlerBinManager.selectDataByPager(start,
                                                                              pageSize=self.crawler_bin_page_size,
                                                                              query_columns=query_columns)
        WithButtonTableWidget(self, self.crawlerBinTableWidget, self.crawler_bin_page_data, self.crawler_bin_headers, 1)
        self.crawlerBinTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

    def crawler_bin_page_down(self):
        self.crawler_bin_page_num += 1
        self.crawler_bin_show_page(self.crawler_bin_page_num)

    def crawler_bin_page_up(self):
        self.crawler_bin_page_num -= 1
        if self.crawler_bin_page_num == 0:
            self.crawler_bin_page_num = 1
        self.crawler_bin_show_page(self.crawler_bin_page_num)

    def indexCrawlerBinByBank(self):
        text = self.ui.plainTextEdit.toPlainText()
        cardLineEdit = self.ui.cardLineEdit.text()
        if len(cardLineEdit) == 0:
            cardLineEdit = None
        cardTypeLineEdit = self.ui.cardTypeLineEdit.text()
        if len(cardTypeLineEdit) == 0:
            cardTypeLineEdit = None
        cardLevelLineEdit = self.ui.cardLevelLineEdit.text()
        if len(cardLevelLineEdit) == 0:
            cardLevelLineEdit = None
        textList = text.splitlines()
        textList = [s.upper() for s in textList]
        if len(textList) == 0 and cardLineEdit is None and cardTypeLineEdit is None and cardLevelLineEdit is None:
            self.crawler_bin_show_page(1)
            return
        # banks = RapidBankManager()
        # bankList = banks.selectListByBank(text, "bank, country_abbr")
        # if bankList is not None and len(bankList) > 0:
        rapidCrawlerBinManager = RapidCrawlerBinManager()
        query_columns = CrawlerBinEnum.getValuesStr()
        self.crawler_bin_page_data = []
        crawler_bin_list = rapidCrawlerBinManager.selectListByBanksAndCondition(textList,
                                                                                cardLineEdit,
                                                                                cardTypeLineEdit,
                                                                                cardLevelLineEdit,
                                                                                query_columns)
        if len(crawler_bin_list) > 0:
            self.crawlerBinTableWidget.clear()
            self.crawler_bin_page_data = crawler_bin_list
            WithButtonTableWidget(self, self.crawlerBinTableWidget, crawler_bin_list, self.crawler_bin_headers, 1)
            # else:
            #     result = get_crawler_bin_total(text, bankList[0][1])
            #     if result is not None:
            #         rapidCrawlerBinManager1 = RapidCrawlerBinManager()
            #         print(f"获取返回 BIN 信息：{result}")
            #         rapidCrawlerBinManager1.batchInsertCrawlerBinByTuple(result, tuple(CrawlerBinEnum.getValuesList()))
            #     else:
            #         QMessageBox.about(self.ui, "error", f'当前 Bin 查无数据')
            #         return
        else:
            QMessageBox.about(self.ui, "error", f'当前银行信息暂无，无法去获得BIN信息')
            return
        self.crawlerBinTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

    def indexByCrawlerBin(self):
        text = self.ui.plainTextEdit.toPlainText()
        cardLineEdit = self.ui.cardLineEdit.text()
        if len(cardLineEdit) == 0:
            cardLineEdit = None
        cardTypeLineEdit = self.ui.cardTypeLineEdit.text()
        if len(cardTypeLineEdit) == 0:
            cardTypeLineEdit = None
        cardLevelLineEdit = self.ui.cardLevelLineEdit.text()
        if len(cardLevelLineEdit) == 0:
            cardLevelLineEdit = None
        textList = text.splitlines()
        if len(textList) == 0 and cardLineEdit is None and cardTypeLineEdit is None and cardLevelLineEdit is None:
            self.crawler_bin_show_page(1)
            return
        print(textList, cardLineEdit, cardTypeLineEdit, cardLevelLineEdit)
        rapidCrawlerBinManager = RapidCrawlerBinManager()
        query_columns = CrawlerBinEnum.getValuesStr()
        self.crawler_bin_page_data = None
        self.crawler_bin_page_data = rapidCrawlerBinManager.selectCrawlerBinByCrawlerBins(textList, cardLineEdit,
                                                                                          cardTypeLineEdit,
                                                                                          cardLevelLineEdit,
                                                                                          query_columns)
        if self.crawler_bin_page_data is not None and len(self.crawler_bin_page_data) > 0:
            self.crawlerBinTableWidget.clear()
            WithButtonTableWidget(self, self.crawlerBinTableWidget, self.crawler_bin_page_data,
                                  self.crawler_bin_headers, 1)
        else:
            QMessageBox.about(self.ui, "error", f'当前 BIN/IIN 查无数据')
            return
        self.crawlerBinTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

    def exportCrawlerBins(self):
        ExportExcelDialog(self.crawler_bin_page_data)
        QMessageBox.about(self.ui, "导出BIN信息", f'导出数据：{len(self.crawler_bin_page_data)} 条')

    def oneClickRetrievalBIN(self):

        rapid = RapidBankManager()
        data = rapid.selectDataByPager(0, 100000, "bank, country_abbr, has_bin",
                                       condition="has_bin is null or has_bin='1' ")
        if data is not None and len(data) > 0:
            for item in data:
                # rapidCrawlerBinManager = RapidCrawlerBinManager()
                # crawler_bins = rapidCrawlerBinManager.selectListByBank(item[0])
                # if len(crawler_bins) > 0:
                #     print(f"{item[0]} 已存在 ：{len(crawler_bins)} 条")
                if item[2] != '1' and item[2] is not None:
                    print(f"{item[0]} 爬取不到 BIN, 上次爬取结果为 {item[2]}")
                    continue
                result = None
                try:
                    result = get_crawler_bin_total(item[0], item[1])
                except Exception as e:
                    traceback.print_exc()
                    continue
                if isinstance(result, list):
                    rapidCrawlerBinManager1 = RapidCrawlerBinManager()
                    print(f"获取返回 BIN 信息1：{result}")
                    rapidCrawlerBinManager1.batchInsertCrawlerBinByTuple(result,
                                                                         tuple(CrawlerBinEnum.getValuesList()))
                    rapidBank = RapidBankManager()
                    rapidBank.updateHasBinStatus(item[0], '200', item[1])
                else:
                    print(f"当前BIN 查无 {item[0]} 银行数据, 返回 {result}")
                    rapidBank = RapidBankManager()
                    rapidBank.updateHasBinStatus(item[0], result, item[1])
                    continue
